package com.linkoog.devtools.mybatis.parse_log;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.ide.CopyPasteManager;
import com.intellij.openapi.project.DumbAware;
import com.linkoog.devtools.mybatis.parse_log.common.MyBatisLogParser;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.awt.datatransfer.StringSelection;
import java.util.List;


public class MybatisLogSqlParseAction extends AnAction implements DumbAware {


    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        String selectedText = getSelectedText(event);
        if (StringUtils.isNotBlank(selectedText)){
            List<String> sqlList = MyBatisLogParser.toSql(selectedText,true);
            if (sqlList != null && !sqlList.isEmpty()){
                StringBuilder builder = new StringBuilder();
                for (String sql : sqlList) {
                    builder.append(sql).append("\n\n");
                }

                CopyPasteManager.getInstance().setContents(new StringSelection(builder.toString()));
            }
        }
    }

    private String getSelectedText(AnActionEvent event){
        Editor editor = event.getData(LangDataKeys.EDITOR);
        if (editor == null){
            return null;
        }

        return editor.getCaretModel().getCurrentCaret().getSelectedText();
    }

    @Override
    public void update(@NotNull AnActionEvent event) {
        String selectedText = getSelectedText(event);
        Presentation presentation = event.getPresentation();
        presentation.setEnabledAndVisible(StringUtils.isNotBlank(selectedText));
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.BGT;
    }
}
